package serviceImpl;

import org.apache.commons.compress.utils.IOUtils;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by 韩朝祥 on 2016/12/20.
 */
public class DownloadView implements View {
    private String fileName;
    private File file;

    public DownloadView(File file){
        this(file,file.getName());
    }

    public DownloadView(File file,String fileName){
        this.fileName = fileName;
        this.file = file;
    }

    @Override
    public String getContentType() {
        return null;
    }

    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        FileInputStream fis = null;
        try{
            fis = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            String name = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("Content-Disposition", "attachment;filename=" + name);
            IOUtils.copy(fis,out);
        }finally {
            IOUtils.closeQuietly(fis);
        }
    }
}
